package com.danco.sn.model.dao;

import java.util.HashSet;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.danco.sn.apientities.IMessage;
import com.danco.sn.apientities.IUser;

public class ConversationDAO extends GenericDAO<IMessage> {

	private static final String SENDER = "sender";
	private static final String ADRESSE = "adresse";

	public ConversationDAO() {
		super(IMessage.class);
	}

	@SuppressWarnings("unchecked")
	public List<IMessage> getConversation(Session session, IUser user1,
			IUser user2) throws HibernateException {
		Criterion criterion1 = Restrictions.eq(ADRESSE, user1);
		Criterion criterion2 = Restrictions.eq(SENDER, user1);
		Criterion criterion3 = Restrictions.eq(ADRESSE, user2);
		Criterion criterion4 = Restrictions.eq(SENDER, user2);
		Criteria criteria = session.createCriteria(IMessage.class)
				.add(Restrictions.or(criterion1, criterion2))
				.add(Restrictions.or(criterion3, criterion4));
		List<IMessage> messageList = criteria.list();
		return messageList;
	}

	// get all people wich i have
	@SuppressWarnings("unchecked")
	public List<IUser> getAllConversation(Session session, IUser user)
			throws HibernateException {
		HashSet<IUser> tempSet = new HashSet<IUser>();
		Criteria criteriaSender = session
				.createCriteria(IMessage.class)
				.setProjection(
						Projections.distinct(Projections.property(SENDER)))
				.add(Restrictions.eq(ADRESSE, user));
		Criteria criteriaAdresse = session
				.createCriteria(IMessage.class)
				.setProjection(
						Projections.distinct(Projections.property(ADRESSE)))
				.add(Restrictions.eq(SENDER, user));
		List<IUser> listUser = criteriaSender.list();
		tempSet.addAll(listUser);
		listUser = criteriaAdresse.list();
		tempSet.addAll(listUser);
		listUser.clear();
		listUser.addAll(tempSet);
		return listUser;

	}
}
